import {
    ElLoading,
    ElMessage,
    ElMessageBox,
    type ElMessageBoxOptions,
    ElNotification,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElDatePicker,
    ElTimePicker,
    ElSwitch,
    ElRadio,
    ElRadioGroup,
    ElCheckbox,
    ElCheckboxGroup,
    ElButton
} from 'element-plus'
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
import { h, reactive, ref, createApp } from 'vue'

// 定义表单项类型
export interface FormItem {
    type: 'input' | 'select' | 'date' | 'time' | 'switch' | 'radio' | 'checkbox'
    label: string
    prop: string
    value?: any
    options?: { label: string; value: any }[]
    placeholder?: string
    rules?: any[]
}

// 定义对话框配置类型
export interface DialogOptions {
    width?: string
    title?: string
    formItems: FormItem[]
    onSubmit?: (formData: any) => void
    onCancel?: () => void
}

export class Feedback {
    private loadingInstance: LoadingInstance | null = null
    static instance: Feedback | null = null
    static getInstance() {
        return this.instance ?? (this.instance = new Feedback())
    }
    // 消息提示
    msg(msg: string) {
        ElMessage.info(msg)
    }
    // 错误消息
    msgError(msg: string) {
        ElMessage.error(msg)
    }
    // 成功消息
    msgSuccess(msg: string) {
        ElMessage.success(msg)
    }
    // 警告消息
    msgWarning(msg: string) {
        ElMessage.warning(msg)
    }
    // 弹出提示
    alert(msg: string) {
        ElMessageBox.alert(msg, '系统提示')
    }
    // 错误提示
    alertError(msg: string) {
        ElMessageBox.alert(msg, '系统提示', { type: 'error' })
    }
    // 成功提示
    alertSuccess(msg: string) {
        ElMessageBox.alert(msg, '系统提示', { type: 'success' })
    }
    // 警告提示
    alertWarning(msg: string) {
        ElMessageBox.alert(msg, '系统提示', { type: 'warning' })
    }
    // 通知提示
    notify(msg: string) {
        ElNotification.info(msg)
    }
    // 错误通知
    notifyError(msg: string) {
        ElNotification.error(msg)
    }
    // 成功通知
    notifySuccess(msg: string) {
        ElNotification.success(msg)
    }
    // 警告通知
    notifyWarning(msg: string) {
        ElNotification.warning(msg)
    }
    // 确认窗体
    confirm(msg: string) {
        return ElMessageBox.confirm(msg, '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
    }
    // 提交内容
    prompt(content: string, title: string, options?: ElMessageBoxOptions) {
        return ElMessageBox.prompt(content, title, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            ...options
        })
    }
    // 打开全局loading
    loading(msg: string) {
        this.loadingInstance = ElLoading.service({
            lock: true,
            text: msg
        })
    }
    // 关闭全局loading
    closeLoading() {
        this.loadingInstance?.close()
    }
    // 表单对话框
    formDialog(options: DialogOptions) {
        // 初始化表单数据
        const formData = reactive(
            options.formItems.reduce((acc, item) => {
                acc[item.prop] = item.value
                return acc
            }, {} as Record<string, any>)
        )

        // 初始化表单验证规则
        const formRules = options.formItems.reduce((acc, item) => {
            if (item.rules) {
                acc[item.prop] = item.rules
            }
            return acc
        }, {} as Record<string, any[]>)

        const formRef = ref()
        const dialogVisible = ref(true)

        const handleSubmit = async () => {
            if (!formRef.value) return
            await formRef.value.validate((valid: boolean) => {
                if (valid) {
                    options.onSubmit?.(formData)
                    dialogVisible.value = false
                }
            })
        }

        const handleCancel = () => {
            dialogVisible.value = false
            options.onCancel?.()
            setTimeout(() => {
                app.unmount()
                container.remove()
                style.remove()
            }, 300)
        }

        const dialog = h(ElDialog, {
            modelValue: dialogVisible.value,
            'onUpdate:modelValue': (val: boolean) => dialogVisible.value = val,
            title: options.title || '表单',
            width: options.width || '50%',
            'onClose': handleCancel,
            class: 'custom-dialog',
            destroyOnClose: true,
            closeOnClickModal: false,
            center: true
        }, {
            default: () => h('div', { class: 'dialog-content' }, [
                h(ElForm, {
                    ref: formRef,
                    model: formData,
                    rules: formRules,
                    labelWidth: '100px',
                    class: 'dialog-form'
                }, [
                    ...options.formItems.map(item => {
                        return h(ElFormItem, {
                            label: item.label,
                            prop: item.prop,
                            rules: item.rules,
                            class: 'dialog-form-item'
                        }, () => {
                            switch (item.type) {
                                case 'input':
                                    return h(ElInput, {
                                        modelValue: formData[item.prop],
                                        'onUpdate:modelValue': (val: any) => formData[item.prop] = val,
                                        placeholder: item.placeholder,
                                        class: 'dialog-input'
                                    })
                                case 'select':
                                    return h(ElSelect, {
                                        modelValue: formData[item.prop],
                                        'onUpdate:modelValue': (val: any) => formData[item.prop] = val,
                                        placeholder: item.placeholder,
                                        class: 'dialog-select'
                                    }, () => item.options?.map(opt => 
                                        h(ElOption, {
                                            label: opt.label,
                                            value: opt.value
                                        })
                                    ))
                                case 'date':
                                    return h(ElDatePicker, {
                                        modelValue: formData[item.prop],
                                        'onUpdate:modelValue': (val: any) => formData[item.prop] = val,
                                        placeholder: item.placeholder,
                                        class: 'dialog-date'
                                    })
                                case 'time':
                                    return h(ElTimePicker, {
                                        modelValue: formData[item.prop],
                                        'onUpdate:modelValue': (val: any) => formData[item.prop] = val,
                                        placeholder: item.placeholder,
                                        class: 'dialog-time'
                                    })
                                case 'switch':
                                    return h(ElSwitch, {
                                        modelValue: formData[item.prop],
                                        'onUpdate:modelValue': (val: any) => formData[item.prop] = val,
                                        class: 'dialog-switch'
                                    })
                                case 'radio':
                                    return h(ElRadioGroup, {
                                        modelValue: formData[item.prop],
                                        'onUpdate:modelValue': (val: any) => formData[item.prop] = val,
                                        class: 'dialog-radio'
                                    }, () => item.options?.map(opt =>
                                        h(ElRadio, {
                                            label: opt.value
                                        }, () => opt.label)
                                    ))
                                case 'checkbox':
                                    return h(ElCheckboxGroup, {
                                        modelValue: formData[item.prop],
                                        'onUpdate:modelValue': (val: any) => formData[item.prop] = val,
                                        class: 'dialog-checkbox'
                                    }, () => item.options?.map(opt =>
                                        h(ElCheckbox, {
                                            label: opt.value
                                        }, () => opt.label)
                                    ))
                            }
                        })
                    }),
                    h('div', { class: 'dialog-footer' }, [
                        h(ElButton, {
                            onClick: handleCancel,
                            class: 'dialog-cancel-btn'
                        }, () => '取消'),
                        h(ElButton, {
                            type: 'primary',
                            onClick: handleSubmit,
                            class: 'dialog-submit-btn'
                        }, () => '确定')
                    ])
                ])
            ]),
            footer: () => null
        })

        // 添加样式
        const style = document.createElement('style')
        style.textContent = `
            .custom-dialog {
                border-radius: 8px;
            }
            .custom-dialog .el-dialog__header {
                margin: 0;
                padding: 20px 24px;
                border-bottom: 1px solid #f0f0f0;
            }
            .custom-dialog .el-dialog__title {
                font-size: 16px;
                font-weight: 500;
                color: #1f2f3d;
            }
            .custom-dialog .el-dialog__body {
                padding: 24px;
            }
            .custom-dialog .el-dialog__footer {
                padding: 16px 24px;
                border-top: 1px solid #f0f0f0;
            }
            .dialog-content {
                max-height: 60vh;
                overflow-y: auto;
            }
            .dialog-form {
                padding: 0 20px;
                position: relative;
            }
            .dialog-form-item {
                margin-bottom: 24px;
            }
            .dialog-form-item:last-child {
                margin-bottom: 32px;
            }
            .dialog-footer {
                text-align: center;
                display: flex;
                justify-content: center;
                gap: 16px;
                margin-top: 8px;
                width: calc(100% - 100px);
                margin-left: 100px;
            }
            .dialog-cancel-btn,
            .dialog-submit-btn {
                min-width: 100px;
                height: 36px;
                font-size: 14px;
            }
            .dialog-input,
            .dialog-select,
            .dialog-date,
            .dialog-time {
                width: 100%;
            }
            .dialog-radio,
            .dialog-checkbox {
                display: flex;
                flex-wrap: wrap;
                gap: 16px;
            }
        `
        document.head.appendChild(style)

        // 将对话框挂载到body
        const container = document.createElement('div')
        document.body.appendChild(container)
        const app = createApp({
            render: () => dialog
        })
        app.mount(container)

        return {
            close: () => {
                dialogVisible.value = false
                setTimeout(() => {
                    app.unmount()
                    container.remove()
                    style.remove()
                }, 300)
            }
        }
    }
}

const feedback = Feedback.getInstance()

export default feedback
